package handler

import (
	"context"
	"github.com/go-errors/errors"
	"goodServer/basic/dao"
	__ "goodServer/basic/proto"
)

type Server struct {
	__.UnimplementedGoodServerServer
}

func (s *Server) GoodList(_ context.Context, req *__.GoodListReq) (*__.GoodListResp, error) {
	list, err := dao.GoodList(req.Page, req.Size)
	if err != nil {
		return nil, errors.New("商品查询失败")
	}
	goodList := []*__.GoodList{}
	for _, good := range list {
		goodList = append(goodList, &__.GoodList{
			Name:     good.Name,
			Url:      good.Url,
			Price:    float32(good.Price),
			GoodType: int64(good.GoodType),
			Sum:      int64(good.Sum),
		})
	}
	return &__.GoodListResp{
		List: goodList,
	}, nil
}

func (s *Server) GoodOss(_ context.Context, req *__.GoodOssReq) (*__.GoodOssResp, error) {
	_, err := dao.GoodUpdateUrl(req.Id, req.Oss)
	if err != nil {
		return nil, err
	}

	return &__.GoodOssResp{
		GoodOss: true,
	}, nil
}

func (s *Server) GoodListOne(_ context.Context, req *__.GoodListOneReq) (*__.GoodListResp, error) {
	good, err := dao.GoodListOne(req.Name)
	if err != nil {
		return nil, err

	}
	goodList := []*__.GoodList{}
	goodList = append(goodList, &__.GoodList{
		Name:     good.Name,
		Url:      good.Url,
		Price:    float32(good.Price),
		GoodType: int64(good.GoodType),
		Sum:      int64(good.Sum),
	})

	return &__.GoodListResp{List: goodList}, err
}

func (s *Server) GoodListRecommend(_ context.Context, req *__.GoodListRecommendReq) (*__.GoodListResp, error) {
	good, err := dao.GoodListR()
	if err != nil {
		return nil, err

	}
	goodList := []*__.GoodList{}
	for _, goods := range good {
		goodList = append(goodList, &__.GoodList{
			Name:     goods.Name,
			Url:      goods.Url,
			Price:    float32(goods.Price),
			GoodType: int64(goods.GoodType),
			Sum:      int64(goods.Sum),
		})
	}
	return &__.GoodListResp{
		List: goodList,
	}, nil
}
